import { createRouter, createWebHistory } from 'vue-router'
import {useUserStore} from "@/stores/index.js";
const routes = [
  {
    path: '/',
    component: () => import('../layout/MainLayout.vue'),
    meta: { requiresAuth: true }, // 需要登录
    children: [
      { path: '', component: () => import('../views/index.vue') },
      { path: 'shiyu', component: () => import('../views/shiyu.vue') },
      { path: 'fishku', component: () => import('../views/fishku.vue') },
      { path: 'fishill', component: () => import('../views/fishill.vue') },
      { path: 'jiankong', component: () => import('../views/jiankong.vue') },
      { path: 'chengzhong', component: () => import('../views/smart-weighing.vue') },
      { path: 'test-pinia', component: () => import('../views/test-pinia.vue') },
    ]
  },
  {
    path: '/denglu',
    component: () => import('../views/denglu.vue'),
    meta: { requiresAuth: false } // 不需要登录
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()

  // 如果路由需要登录验证
  if (to.meta.requiresAuth !== false) {
    // 检查是否已登录
    if (!userStore.isAuthenticated) {
      // 尝试自动登录（如果有 token）
      const autoLoginSuccess = await userStore.autoLogin()

      if (!autoLoginSuccess) {
        // 自动登录失败，重定向到登录页面
        next('/denglu')
        return
      }
    }
  }
  // 如果已登录用户访问登录页面，重定向到首页
  if (to.path === '/denglu' && userStore.isAuthenticated) {
    next('/')
    return
  }

  next()
})

export default router
